from fastapi import FastAPI, HTTPException
import uvicorn
from pydantic import BaseModel
from functools import lru_cache

app = FastAPI(title="斐波那契数列服务API")

class FibonacciInput(BaseModel):
    n: int
    use_cache: bool = True

@lru_cache(maxsize=1000)
def cached_fib(n: int) -> int:
    """带缓存的递归实现"""
    if n <= 1:
        return n
    return cached_fib(n-1) + cached_fib(n-2)

def iterative_fib(n: int) -> int:
    """迭代实现"""
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(1, n):
        a, b = b, a + b
    return b

@app.post("/fibonacci")
async def fibonacci_endpoint(input: FibonacciInput):
    """计算斐波那契数"""
    if input.n < 0:
        raise HTTPException(
            status_code=400,
            detail="请输入非负整数"
        )
    
    if input.use_cache:
        result = cached_fib(input.n)
        method = "cached_recursive"
    else:
        result = iterative_fib(input.n)
        method = "iterative"
    
    return {
        "position": input.n,
        "fibonacci_number": result,
        "method": method,
        "performance_note": "使用缓存可显著提高递归性能" if input.use_cache else "迭代方法适合大数计算"
    }

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8001)  # 使用不同端口